<template>
  <div :class="$style.wrap">
    <FormContainer :column="4">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="生日核对" prop="checkInfo" :span="24">
          <!-- <CalendarPickerPane v-model="formData.checkInfo" :type.sync="checkInfoType" placeholder="请选择生日"></CalendarPickerPane> -->
          <!-- <el-input v-model="formData.checkInfo" placeholder="请输入核对生日，如：2020-11-02" clearable></el-input> -->
          <CustomDictSelect
            placeholder="请选择核对信息"
            dict-type-code="KQ_BIRTHDAY_CHECK"
            bind-name="dictName"
            bind-value="dictCode"
            :echo-value.sync="formData.checkInfo"
            style="width: 25%"
          ></CustomDictSelect>
        </el-form-item>
        <template v-for="(item, index) in formData.careTaskGiftList">
          <el-form-item
            :key="index"
            :prop="'careTaskGiftList.' + index + '.giftCode'"
            label="礼品名称"
            :span="24/6"
          >
            <SearchSelectPicker
              url="/call-center/api/v1/careGift/page"
              placeholder="请选择礼品"
              lable-name="giftName"
              value-name="giftCode"
              :params="{query:{quantity: {operator:'>=', value:1}}, type: 0}"
              :value.sync="item.giftCode"
              :lable.sync="item.giftName"
              :current-id.sync="item.giftId"
            ></SearchSelectPicker>
          </el-form-item>
          <el-form-item
            :key="index + 'quantity'"
            :span="24/7"
            :prop="'careTaskGiftList.' + index + '.quantity'"
            label="礼品数量"
          >
            <el-select
              v-model="item.quantity"
              placeholder="请选择"
              filterable
              clearable
            >
              <el-option
                v-for="(list, key) in 6"
                :key="key"
                :label="list"
                :value="list"
              />
            </el-select>
          </el-form-item>
          <el-form-item :key="index + 'sendDate'" :prop="'careTaskGiftList.' + index + '.sendDate'" label="发放日期" :span="24/6">
            <el-date-picker v-model="item.sendDate" type="date" placeholder="选择发放日期" clearable></el-date-picker>
          </el-form-item>
          <el-form-item :key="index + 'expressNo'" label="快递单号" :prop="'careTaskGiftList.' + index + '.expressNo'" :span="24/6">
            <el-input v-model="item.expressNo" placeholder="请输入快递单号" clearable></el-input>
          </el-form-item>
          <el-form-item :key="index + 'receiptDate'" :prop="'careTaskGiftList.' + index + '.receiptDate'" label="签收日期" :span="24/6">
            <el-date-picker v-model="item.receiptDate" type="date" placeholder="选择发签收日期" clearable></el-date-picker>
          </el-form-item>
          <el-form-item :key="index + 'svg'" :span="24/7">
            <svg
              v-if="index === formData.careTaskGiftList.length-1"
              :class="$style.icon"
              aria-hidden="true"
              @click="addItem"
            >
              <use xlink:href="#tianjiaxinjian" />
            </svg>
            <svg
              v-if="formData.careTaskGiftList.length!==1"
              :class="[$style.icon, $style.delete]"
              aria-hidden="true"
              @click="deleteItem(item, index)"
            >
              <use xlink:href="#shanchulajixiang-line" />
            </svg>
          </el-form-item>
        </template>
        <el-form-item label="签收人" prop="consignee">
          <el-input v-model="formData.consignee" placeholder="请输入签收人" clearable></el-input>
        </el-form-item>
        <el-form-item prop="defaultAddress" label="默认收货地址" :span="24">
          <el-input v-model="formData.defaultAddress" placeholder="请输入默认收货地址" type="textarea" :autosize="{minRows:1}" clearable disabled></el-input>
        </el-form-item>
        <!-- <el-form-item prop="province" label="客情收货地址">
          <Address v-model="formData.province" :name.sync="formData.provinceName" label="省" init placeholder="请选择省" clearable filterable></Address>
        </el-form-item>
        <el-form-item prop="city" label="市">
          <Address v-model="formData.city" :name.sync="formData.cityName" :parent="formData.province" placeholder="请选择市" clearable filterable></Address>
        </el-form-item>
        <el-form-item prop="county" label="区/县">
          <Address v-model="formData.county" :name.sync="formData.countyName" :parent="formData.city" placeholder="请选择区/县" clearable filterable></Address>
        </el-form-item>
        <el-form-item prop="street" label="街道">
          <Address v-model="formData.street" :name.sync="formData.streetName" :parent="formData.county" placeholder="请选择街道" clearable filterable></Address>
        </el-form-item>
        <el-form-item prop="detailAddress" label="详细地址" :span="24">
          <el-input v-model="formData.detailAddress" placeholder="请输入详细地址" type="textarea" :autosize="{minRows:1}" clearable></el-input>
        </el-form-item> -->
        <el-form-item prop="detailAddress" label="客情收货地址" :span="24">
          <el-input v-model="formData.detailAddress" placeholder="请输入客情收货地址" type="textarea" :autosize="{minRows:1}" clearable></el-input>
        </el-form-item>
        <el-form-item prop="blessingWords" label="祝福语" :span="24">
          <el-input v-model="formData.blessingWords" placeholder="请输入祝福语" type="textarea" :autosize="{minRows:3}" clearable></el-input>
        </el-form-item>
        <el-form-item prop="remarks" label="备注" :span="24">
          <el-input v-model="formData.remarks" placeholder="请输入备注" type="textarea" :autosize="{minRows:3}" clearable></el-input>
        </el-form-item>
        <el-form-item label="附件" prop="careTaskAnnexList">
          <DialogUpload
            action="/"
            title="选取文件"
            text="选取文件"
            :click-down="false"
            :auto-upload="false"
            :destroy="false"
            multiple
            :on-change="onFileChange"
            :on-remove="onFileChange"
            :before-remove="beforeRemove"
            confirm-button-text="添加附件"
            :exist-file-list="formData.careTaskAnnexList"
          />
        </el-form-item>
        <el-form-item v-if="$route.query.type!=='preview'&&!disabled" :span="24">
          <div class="button-container" style="padding-top: 0">
            <Button type="primary" @click="save">暂存礼物信息</Button>
            <Button type="primary" @click="submitHandle">提交</Button>
          </div>
        </el-form-item>
      </el-form>
    </FormContainer>
  </div>
</template>
<script>
import FormContainer from '@/components/FormContainer'
import CustomDictSelect from '@/components/CustomDictSelect'
// import CalendarPickerPane from '@/components/CalendarPickerPane'
import SearchSelectPicker from '@/components/SearchSelectPicker'
// import Address from '@/components/Address'
import DialogUpload from '@/components/Upload/DialogUpload'
import { submitGift, saveGift, deleteAnnex } from '@/api/guestCare'
// import { deepCopy, parseTime, date2Str, ls } from '@/utils'
import { deepCopy, parseTime } from '@/utils'
export default {
  name: 'CareGift',
  components: {
    FormContainer,
    // CalendarPickerPane,
    SearchSelectPicker,
    // Address,
    DialogUpload,
    CustomDictSelect
  },
  props: {
    info: {
      type: Object,
      default: () => ({})
    },
    careInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    // const validatorCheckInfo = (r, v, c) => {
    //   if (v === '' || v === undefined || v === null) {
    //     c()
    //   } else if (/^(\d{4}-[01]{1}[012]{1}-[012]{1}[0-9]{1})|(\d{4}-[01]{1}[012]{1}-3[01]{1})$/.test(v)) {
    //     c()
    //   } else {
    //     c(new Error('年月日分隔符为短横线'))
    //   }
    // }
    return {
      checkInfoType: '',
      existFileList: '',
      formData: {
        checkInfo: '',
        careTaskGiftList: [],
        consignee: '',
        province: '',
        provinceName: '',
        city: '',
        cityName: '',
        county: '',
        countyName: '',
        street: '',
        streetName: '',
        detailAddress: '',
        blessingWords: '',
        remarks: '',
        careTaskAnnexList: [],
        defaultAddress: ''
      },
      formRules: {
        // checkInfo: [{ validator: validatorCheckInfo, trigger: 'change' }]
      },
      // 礼物结构
      giftItem: { giftCode: '', giftId: '', giftName: '', quantity: '', sendDate: '', expressNo: '', receiptDate: '' },
      // 附件结构
      annexItem: { fileName: '', filePath: '', fileSize: '', fileType: '' }
    }
  },
  computed: {
    disabled() {
      return this.info.giftState === 1 || this.info.giftState === '1'
    }
  },
  watch: {
    info: {
      handler() {
        for (const fKey of Object.keys(this.formData)) {
          const v = this.info[fKey]
          if (v === undefined || v === null) {
            continue
          }
          // 礼物
          if (fKey === 'careTaskGiftList') {
            const careTaskGiftList = []
            if (v && v.length > 0) {
              for (const item of v) {
                const gi = deepCopy(this.giftItem)
                for (const key of Object.keys(gi)) {
                  gi[key] = item[key] || ''
                }
                careTaskGiftList.push(gi)
              }
            } else {
              const t = deepCopy(this.giftItem)
              // t.taskId = this.info.id
              careTaskGiftList.push(deepCopy(t))
            }
            this.$set(this.formData, 'careTaskGiftList', careTaskGiftList)
            continue
          }
          // 附件
          if (fKey === 'careTaskAnnexList') {
            const careTaskAnnexList = []
            if (this.info.careTaskAnnexList) {
              for (const item of this.info.careTaskAnnexList) {
                item.name = item.fileName
                item.url = item.filePath
                careTaskAnnexList.push(item)
              }
            }
            this.$set(this.formData, 'careTaskAnnexList', careTaskAnnexList)
            continue
          }
          // if (fKey === 'checkInfo') {
          //   if (v.includes('公历')) {
          //     const date = v.replace(/\(.*\)/, '')
          //     this.$set(this, 'checkInfoType', 'solar')
          //     this.$set(this.formData, fKey, ls(date, 'solar'))
          //   } else if (v.includes('农历')) {
          //     const date = v.replace(/\(.*\)/, '')
          //     this.$set(this, 'checkInfoType', 'lunar')
          //     this.$set(this.formData, fKey, ls(date, 'lunar'))
          //   }
          //   continue
          // }
          this.$set(this.formData, fKey, this.$numToString(v))
        }
      },
      immediate: true
    }
  },
  methods: {
    // 增加表单Item
    addItem() {
      const t = deepCopy(this.giftItem)
      // t.taskId = this.info.id
      this.formData.careTaskGiftList.push(t)
    },
    // 删除动态Item
    deleteItem(item, index) {
      this.formData.careTaskGiftList.splice(index, 1)
    },
    // 暂存
    save() {
      return this.$refs.form.validate().then(() => {
        const data = this.genQuery()
        if (data === false) {
          return
        }
        return saveGift(data).then(res => {
          this.$message.success('暂存成功！')
          this.$emit('on-success')
        })
      })
    },
    submitHandle() {
      return this.$refs.form.validate().then(() => {
        const data = this.genQuery()
        if (data === false) {
          return
        }
        return submitGift(data).then(res => {
          this.$message.success('提交成功！')
          this.$emit('on-success')
        })
      })
    },
    // 生成参数
    genQuery() {
      const data = deepCopy(this.formData)
      // if (this.checkInfoType === 'solar') {
      //   data.checkInfo = `${date2Str(this.formData.checkInfo, this.checkInfoType)}(公历)`
      // } else if (this.checkInfoType === 'lunar') {
      //   data.checkInfo = `${date2Str(this.formData.checkInfo, this.checkInfoType)}(农历)`
      // }
      data.id = this.info.id
      data.careMode = this.careInfo.careMode.join(',')
      data.careModeName = this.careInfo.careModeName
      const formData = new FormData()
      for (const key of Object.keys(data)) {
        if (data[key] === undefined || data[key] === null || data[key] === '') {
          continue
        }
        if (key === 'careTaskAnnexList') {
          data[key].forEach(e => {
            if (e.raw) {
              formData.append('files', e.raw)
            }
          })
        } else if (key === 'careTaskGiftList') {
          if ((data[key]).length > 0) {
            for (let i = 0; i < data[key].length; i++) {
              const v = data[key][i]
              if (v === undefined || v === null || v === '') {
                continue
              }
              // 礼品检测
              for (const k of Object.keys(v)) {
                if (k === 'giftCode' || k === 'quantity') {
                  if (v.giftCode === '') {
                    this.$message.info('礼品名称不能为空！')
                    return false
                  }
                  if (v.quantity === '') {
                    this.$message.info('礼品数量不能为空！')
                    return false
                  }
                }
                if ((k === 'sendDate' || k === 'receiptDate') && v[k] instanceof Date) {
                  formData.append(`careTaskGiftList[${i}].${k}`, parseTime(v[k], '{y}-{m}-{d}'))
                } else {
                  formData.append(`careTaskGiftList[${i}].${k}`, v[k] || '')
                }
              }
            }
          }
        } else {
          formData.append(key, data[key])
        }
      }
      return formData
    },
    // 附件
    // 选择的文件发生变化
    onFileChange(file, fileList) {
      this.$set(this.formData, 'careTaskAnnexList', fileList)
      // this.$set(this.formData, 'emailAnnexList', fileList)
    },
    // 删除签
    beforeRemove(file, fileList) {
      return this.$msgbox({
        title: '提示',
        message: '确认删除？',
        showCancelButton: true,
        type: 'warning'
      }).then(() => {
        if (file.raw) {
          return Promise.resolve()
        }
        return deleteAnnex(file.id).then(res => {
          this.$message.success('删除成功！')
        })
      })
    }
  }
}
</script>
<style lang='scss' module>
.wrap{
.icon {
  width: 1.3em;
  height: 1.3em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
  color: #16bc83;
  cursor: pointer;
  margin: 5px;
}
.delete {
  color: red !important;
}
}
</style>
